﻿using System;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Matrix.Common.Utility;
using Matrix.Common.Utility.Files;
using Matrix.MaKaYunShang.ApiService.Controllers;
using Matrix.MaKaYunShang.BLL;
using Matrix.MaKaYunShang.BLL.BllExt;
using Matrix.MaKaYunShang.BLL.CloudCard;
using Matrix.MaKaYunShang.BLL.WxInterfaceFunc;
using Matrix.MaKaYunShang.Model;
using Matrix.MaKaYunShang.Model.Dto;
using Microsoft.VisualStudio.TestTools.UnitTesting;

using Matrix.MaKaYunShang.Model.Enum;
namespace Matrix.MaKaYunShang.ApiServiceTest
{
    [TestClass]
    public class UnitTest1
    {
        private readonly ConsumerBLL _consumerBll = new ConsumerBLL();
        private readonly SysConfigApiController sysConfigApiController = new SysConfigApiController();
        private readonly ShopApiController _shopApiController = new ShopApiController();

        protected readonly MatrixCloudCenterInterFuncBll MatrixCloudCenterInterFuncBllObj =
            new MatrixCloudCenterInterFuncBll();

        private CloudCardBll _cloudCardBll = new CloudCardBll();
        [TestMethod]
        public void testtt2222()
        {
            var strResultJson = HttpClientHelper.PostResponse("http://cloudcenter.icloudmatrix.com/api/WechatMsg/GetMsgRobotWorkReply?replyType=1&mcId=Y000002&random=4V24L8ZV&checkCode=16B413B59E053F20503407420C947CA4", "8A41A174EFF4B43B0F9EEBA7EB175DCC1ED2BC378A14A61B8511A802480575D30821CEEBBE5C9C9AF75AB4CCBCA9A3B4F6EB5887A3703558001B6637E620A697A6781A7240612EAC7901CF526AFE766C740DAC4BB8DE74FA7AB359ED07C8E67731D636A2CE3974C0EF0F9578517B85F3AB40E266DDD380AF1AC3B6AA67D6D4C905FC12DA9E0BC5D98B7035DD11DCC47E7120F38CA9A4DC4513C36C1D91C8D33E629A772E1F8433A8");

            //double _x = double.Parse("104.10428083185");
            //double _y = double.Parse("30.612092681601");
            //double[] bd = CoordinateTransform.BD_WG84(_x, _y);
            //string ss = string.Format("转换后的经纬度是:{0},{1}<br />", bd[0], bd[1]);

        }

        [TestMethod]
        public void testtt()
        {

            UserCardBLL.Instance.GetUserCardList(1, 1, 1, 1);

            CommodityLibBLL.Instance.GetPagingList(1, 1, 1, null, "");

            //WxInterCardFunc wxInterCardFunc = new WxInterCardFunc();
            //var s = wxInterCardFunc.GetWxToken("wxd14082c915b463a3", "f8a341646e16b0249ce859b25c906bf4", "1");
            //wxInterCardFunc.GetMemberCardUserInfo(s, "pzfDSw5vGujYPt9h1q5RjyHbmZpk", "885318928012");

            //var order = OrdersBLL.Instance.GetModel(5924);
            //SendShareRedEnvelope(order);
        }
        /// <summary>
        /// 发送分享红包
        /// </summary>
        /// <param name="orderToUpdate"></param>
        private void SendShareRedEnvelope(Orders orderToUpdate)
        {
            if (orderToUpdate.OrderStatus == (int)CommonEnum.OrderStatus.Finished)
            {
                try
                {

                    var strShareTokenDecryped = EncryptionLib.Decrypt(orderToUpdate.ShareToken);
                    var arrShareToken = strShareTokenDecryped.Split('_');
                    if (arrShareToken.Length == 4)
                    {
                        if (arrShareToken[1] != "shareplatform" || arrShareToken[3].Length < 4)
                        {
                            return;
                        }

                        int nTime;
                        if (!int.TryParse(arrShareToken[2], out nTime))
                        {
                            return;
                        }
                        var nConsumerId = int.Parse(arrShareToken[0]);

                        var sysConfigInfo = SysConfigBLL.Instance.GetModelList();
                        if (sysConfigInfo == null || sysConfigInfo.Count == 0 || sysConfigInfo[0].Id == 0 ||
                            !sysConfigInfo[0].IsSendShareRedEnvolope)
                        {
                            return;
                        }

                        var consumerInfo = _consumerBll.GetModel(nConsumerId);
                        if (consumerInfo == null || consumerInfo.Id == 0)
                        {
                            return;
                        }

                        //var wechatUserInfo = WechatUserBLL.Instance.GetModel(consumerInfo.WechatUserId);
                        //if (wechatUserInfo == null || wechatUserInfo.Id == 0 ||
                        //    string.IsNullOrWhiteSpace(wechatUserInfo.OpenId))
                        //{
                        //    return;
                        //}

                        //var bCheck = WeChatRedEnvelopeTaskBLL.Instance.CheckShareTokenExist(orderToUpdate.ShareToken);
                        //if (bCheck) return;
                        //var newEnvelopeTask = new WeChatRedEnvelopeTask
                        //{
                        //    WechatInfoId = wechatUserInfo.WeChatInfoId,
                        //    OpenIdToPay = wechatUserInfo.OpenId,
                        //    Amount = sysConfigInfo[0].MinRedEnvolopeOfShare,
                        //    PaySource = 1,
                        //    OrderNo = orderToUpdate.OrderNo,
                        //    ShareToken = orderToUpdate.ShareToken,
                        //    IsSend = false,
                        //    AddTime = DateTime.Now,
                        //    IsDelete = false
                        //};
                        //WeChatRedEnvelopeTaskBLL.Instance.AddNewShareRedTask(newEnvelopeTask);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("OrderApiController | SendShareRedEnvelope | Cannot send share red monty " +
                                           orderToUpdate.ShareToken + " Exception: " + ex.Message + ex.StackTrace);
                }

            }
        }
        int ShopId = 3228;
        [TestMethod]
        public void TestMethod1()
        {
            var modelList = ShopsBLL.Instance.GetModelListdt(" IsActive='true' and IsDelete=0 and Enabled='true'");

            NpoiHelper.ExportDTtoExcel(modelList, "店铺里列表", @"D:\新建文件夹\shoplist.ods");
        }
        /// <summary>
        /// 临时方法：去除指定商品的提现价格
        /// </summary>
        /// <param name="totalIncomeOfShopId"></param>
        /// <param name="totalWithdrawCashByShopId"></param>
        /// <returns></returns>
        private double GetCashWithdrawalAmount(double totalIncomeOfShopId, double totalWithdrawCashByShopId)
        {
            var orderExtBll = new OrderExtBll();
            //算出虚拟商品的总价格
            var dVituralOrderCommodityTotalPrice =
                orderExtBll.GetOrderVirtualCommodityTotalPriceOfShop(ShopId);
            //TODO: 提现时临时屏蔽30周年套餐商品购买金额 CommodityLib Id= 1
            var lsExceptOrders = orderExtBll.GetOrderListByCommodityLibId(ShopId, 1);
            if (lsExceptOrders != null && lsExceptOrders.Count > 0)
            {
                decimal dLeftPriceFromExceptOrders = 0;
                var dExceptCommodityPrice = ShopCommodityBLL.Instance.GetModelByShopIdAndCommodityId(ShopId, 1);
                dLeftPriceFromExceptOrders = lsExceptOrders.Sum(order => order.DiscountPrice - dExceptCommodityPrice.SoldPrice);
                dLeftPriceFromExceptOrders = dLeftPriceFromExceptOrders < 0 ? 0 : dLeftPriceFromExceptOrders;
                totalIncomeOfShopId = totalIncomeOfShopId - Convert.ToDouble(lsExceptOrders.Sum(p => p.DiscountPrice)) +
                                   Convert.ToDouble(dLeftPriceFromExceptOrders);
                totalIncomeOfShopId = totalIncomeOfShopId < 0 ? 0 : totalIncomeOfShopId;
            }

            var nCashWithdrawalAmount = totalIncomeOfShopId - totalWithdrawCashByShopId -
                                        dVituralOrderCommodityTotalPrice;
            nCashWithdrawalAmount = nCashWithdrawalAmount < 0 ? 0 : nCashWithdrawalAmount;
            return nCashWithdrawalAmount;
        }

        [TestMethod]
        public void TestMethod2()
        {

            var strEncode = EncryptionLib.Encrypt(4 + "" + 0);
            var api = new OrderApiController();

            api.SendOrderCouponToCustomer(2348, 3511);
        }

        [TestMethod]
        public void TestMethod3()
        {
            var strJson = "ACEDCD2EB439E90D47BDDB16B736EAF5F76EE9C1469B0E2FA57AE5245D4CDD0C867C1CBFFD6DD41AD5E30DA018AB287625BC778DA737479DB1AD70C3CB19EB146379B19637AA31982BBADDA6E2516F1C9B2D95CF2D5498F83BDF301DC0242266DA32ABB0F98C786BCAB54F52BF0D89FBE8092E964BFFEC2E4AF54D5868BE24714E2C294A9C02188DF1E6E6E376AB3B5E4D9D11E32617138D25809F447C1FE856A7F5210B958F1346CE602DD83F6EB5AFD02DF98E702400744E881EBF50D3C5FB8FB9153ABA026E3C21215CC0C353FDAD60F9D144CB78DBB268C90458C5DB0743DC301477900B432BABDB5B6C7EA2A0300D582A5AD267785789162D0CCD441B2E9A9D96D309E944783985EBB2AA4548273834F3E30C830A99A5C40BAA1FE5C50BC06AD26EF2608DA988500EA83EE966E04EB6C68332993DE99FB1F0AB6D089721F6CBBD7E3E82310CCC0D1067D3E9095862BB584F1AB5B3F6EDBA68B2BA3A60A32A413158740C21045EC9983E65AC5E51DB0195E8EA604388A41653E22206B158069E9D08DA48028AD30E1BF550064AE8F5FF70227ECF5E37B81E2384818DFE1FBFE032481E0246E3A41653E22206B158F155BE7317A75D68E8F3E0EFD8FBD40F478AEEB3E15E3E1C0951D1426FBF362F358CF78D3F4A0345BFD83BCC168FE5D167168563C35C5E1236BC877EAE8D1827D30C47ED3B77C41951F0FBD930E868274D85C30C210718AA4748819E4886FE025828CE0E4D48128877302D3577947444863609CD819E00CD20707DB4B110E457D6DC67FFEA18C464930C695D86931B57D40E55160A3695318066D1B2DBA2F5582803D60E4FB91CAE229C8FDE5EA8FB9A3014563E2EA233A4229C8FDE5EA8FB9A3232CF6CEE4B79E6AD8F6DF5199847AE107E4FABB71C49DDC6E9336DF1F7729C76FB26EC0CC08614";

            //var ddd = JsonTool.JsonToObj<OuterOrderDto>(strJson);

            var con = new OrderApiController();

            con.AddNewConsumerOrder(strJson);
        }

        public double CalcRange(double lon1, double lat1, double lon2, double lat2)
        {
            //计算两点距离
            double DEF_PI = 3.14159265359; // PI
            double DEF_2PI = 6.28318530712; // 2*PI
            double DEF_PI180 = 0.01745329252; // PI/180.0
            double DEF_R = 6370693.5; // radius of earth
            //计算短距离
            double ew1, ns1, ew2, ns2;
            double dx, dy, dew;
            double distance;
            // 角度转换为弧度
            ew1 = lon1 * DEF_PI180;
            ns1 = lat1 * DEF_PI180;
            ew2 = lon2 * DEF_PI180;
            ns2 = lat2 * DEF_PI180;
            // 经度差
            dew = ew1 - ew2;
            // 若跨东经和西经180 度，进行调整
            if (dew > DEF_PI)
                dew = DEF_2PI - dew;
            else if (dew < -DEF_PI)
                dew = DEF_2PI + dew;
            dx = DEF_R * Math.Cos(ns1) * dew; // 东西方向长度(在纬度圈上的投影长度)
            dy = DEF_R * (ns1 - ns2); // 南北方向长度(在经度圈上的投影长度)
            // 勾股定理求斜边长
            distance = Math.Sqrt(dx * dx + dy * dy);
            return distance;
        }

        public string GetOrderAmountByStatus(string countColumnName, bool ignoreDelete, bool isGroupbyConsumerId, bool isGroupbyShopId,
            bool isGroupByOrderStatus, bool isOrderByAmountDesc, int consumerId = 0, int shopId = 0, int orderStatus = -1)
        {
            var strSql = "SELECT COUNT(Id) AS {0} {1} FROM ORDERS {2} {3} {4}";

            var strColumnGroupby = string.Empty;
            if (isGroupbyConsumerId)
            {
                strColumnGroupby += "ConsumerId";
            }
            if (isGroupbyShopId)
            {
                strColumnGroupby += ", ShopId";
            }
            if (isGroupByOrderStatus)
            {
                strColumnGroupby += ", OrderStatus";
            }
            var strGroupBy = string.Empty;
            if (!string.IsNullOrWhiteSpace(strColumnGroupby))
            {
                strGroupBy = "GROUP BY " + strColumnGroupby;
            }

            var strOrderBy = "ORDER BY " + countColumnName + (isOrderByAmountDesc ? " DESC" : " ASC");

            if (!string.IsNullOrWhiteSpace(strColumnGroupby))
            {
                countColumnName += ", ";
            }

            var strWhere = string.Empty;
            if (consumerId > 0)
            {
                strWhere += "ConsumerId=" + consumerId + " ";
            }

            if (shopId > 0)
            {
                strWhere += (string.IsNullOrWhiteSpace(strWhere) ? "" : " AND ") + "ShopId=" + shopId;
            }
            if (orderStatus > -1)
            {
                strWhere += (string.IsNullOrWhiteSpace(strWhere) ? "" : " AND ") + "OrderStatus=" +
                                     orderStatus;
            }
            if (ignoreDelete)
            {
                strWhere += (string.IsNullOrWhiteSpace(strWhere) ? "" : " AND ") + "IsDelete=0";
            }

            strWhere = string.IsNullOrWhiteSpace(strWhere) ? "" : ("WHERE " + strWhere);

            return string.Format(strSql, countColumnName, strColumnGroupby, strWhere, strGroupBy,
                strOrderBy);
        }

        [TestMethod]
        public void GetConsumerShopIdTest()
        {
            var consumerApi = new ConsumerApiController();
            var consumerId = 7;
            var shopTel = "15388269408";
            var consumerMobile = "13540545486";
            var consumerAddress = "锦东路668号国嘉新世界3栋1801";
            var verifyCode = EncryptionLib.Encrypt(consumerId + shopTel + consumerMobile + consumerAddress);
            //var result = consumerApi.GetConsumerShopId(consumerId, verifyCode, shopTel, consumerMobile, consumerAddress);
            //result = null;
        }

        [TestMethod]
        public void AddCommentTest()
        {
            var orderApi = new OrderApiController();
            var consumerId = 5;
            var orderId = 1;
            var points = 4;
            var content = "好评";
            var verifyCode = EncryptionLib.Encrypt(consumerId.ToString() + orderId + points + content);
            var result = orderApi.AddComment(consumerId, orderId, points, content, verifyCode);
            result = null;
        }

        [TestMethod]
        public void GetCousumerOperableOrderListTest()
        {
            var orderApi = new OrderApiController();
            var consumerId = 9;
            var verifyCode = EncryptionLib.Encrypt(consumerId.ToString());
            //var result = orderApi.GetCousumerOperableOrderList(consumerId, verifyCode);
            //result = null;
        }

        [TestMethod]
        public void GetRandomPayDiscountTest()
        {
            //var discount = SysPayDiscountConfigBLL.Instance.GetRandomPayDiscount(2);
            //if (discount != 0)
            //{
            //    discount = 0;
            //}
        }

        [TestMethod]
        public void SendSMSTest()
        {
            var mobile = "";
            var source = 7;
            var verify = EncryptionLib.Encrypt(mobile + 7);

        }

        [TestMethod]
        public void GetShopCanCardTest()
        {
            var shopid = 1776;
            var cardList = _shopApiController.GetShopCanCard(shopid);
            if (cardList.Data != null)
            {
                cardList = null;
            }
        }
    }
}
